package nl.hengelsportmolenberg.boilies.client.presenter;

import java.util.List;

import nl.hengelsportmolenberg.boilies.client.BoiliesServiceAsync;
import nl.hengelsportmolenberg.boilies.client.event.EditCustomerEvent;
import nl.hengelsportmolenberg.boilies.shared.CustomerCard;
import nl.hengelsportmolenberg.boilies.shared.OrderDetails;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class CustomerCardPresenter implements Presenter {
	
	private List<OrderDetails> orderDetails;
	private CustomerCard customerCard;
	
	public interface Display {
	    HasClickHandlers getAddOrderButton();
	    HasClickHandlers getEditCustomerButton();
	    HasClickHandlers getList();
	    void setData(CustomerCard card);
	    int getClickedRow(ClickEvent event);
	    Widget asWidget();
	}
	
	private final BoiliesServiceAsync rpcService;
	private final HandlerManager eventBus;
	private final Display display;
	
	public CustomerCardPresenter(BoiliesServiceAsync rpcService, HandlerManager eventBus, Display view) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = view;
	}

	public void bind() {
		display.getAddOrderButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				System.out.println("Add order button clicked");
			}
		});
		
		display.getEditCustomerButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new EditCustomerEvent(customerCard.getId()));
			}
		});
		
		display.getList().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				int selectedRow = display.getClickedRow(event);
		        
		        if (selectedRow >= 0) {
		          int id = orderDetails.get(selectedRow).getId();
					System.out.println("Edit order button for order: "+id+" clicked");
		        }
		    }
		});
	}
	
	public void go(final HasWidgets container) {
		bind();
		container.clear();
		container.add(display.asWidget());
		fetchCustomerCard();
	}
	
	private void fetchCustomerCard() {
		rpcService.getCustomerCard(1, new AsyncCallback<CustomerCard>() {
			public void onSuccess(CustomerCard result) {
				display.setData(result);
				customerCard = result;
			}
		      
		      public void onFailure(Throwable caught) {
		        Window.alert("Error fetching contact details");
		      }
		    });
		  }
}
